package cn.tedu.cwfw.client.service.impl;

import cn.tedu.cwfw.base.exception.ServiceException;
import cn.tedu.cwfw.base.response.StatusCode;
import cn.tedu.cwfw.client.mapper.ClientMapper;
import cn.tedu.cwfw.client.pojo.dto.ClientLoginParam;
import cn.tedu.cwfw.client.pojo.dto.ClientQuery;
import cn.tedu.cwfw.client.pojo.dto.ClientSaveParam;
import cn.tedu.cwfw.client.pojo.entity.Client;
import cn.tedu.cwfw.client.pojo.vo.ClientVO;
import cn.tedu.cwfw.client.service.ClientService;
import cn.tedu.cwfw.client.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class ClientServiceImpl implements ClientService {
    @Autowired
    ClientMapper clientMapper;

    @Override
    public ClientVO login(ClientLoginParam clientLoginParam) {
        log.debug("用户登录：userLoginParam={}",clientLoginParam);
        ClientVO clientVO = clientMapper.selectByUsername(clientLoginParam.getUsername());
        if (clientVO==null){
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if (!clientVO.getPassword().equals(clientLoginParam.getPassword())){
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        // 登录成功以后 返回token   前端发送登录请求的回调函数中保存到localStorage
        // axios.post('/login',{username:'',password:''}).then(res=>{在这里存储到localStorage})  前端发送普通请求的时候  把token是不是放到header
        // ，后端要做拦截器，判断是否登录，如果没有登录，就跳转到登录页面
        Map<String,Object> map = new HashMap<>();
        map.put("username", "jx");
        String token = JWTUtil.getToken(map);
        JWTUtil.verify(token);
        clientVO.setToken(token);
        return clientVO;
    }

    @Override
    public void saveClient(ClientSaveParam clientSaveParam) {
        Client client = new Client();
        BeanUtils.copyProperties(clientSaveParam,client);
        if (client.getId()==null){
            log.debug("用户注册：userSaveParam={}",clientSaveParam);
            client.setPassword("123456");
            client.setCreateTime(new Date());
            clientMapper.insert(client);
        }else {
            log.debug("用户更新：userSaveParam={}",clientSaveParam);
            client.setUpdateTime(new Date());
            clientMapper.update(client);
        }
    }

    @Override
    public void deleteClient(Long clientId) {
        log.debug("删除用户业务，参数：{}",clientId);
        clientMapper.deleteById(clientId);
    }

    @Override
    public List<ClientVO> selectClient(ClientQuery clientQuery) {
        log.debug("查询用户业务，参数：{}",clientQuery);
        List<ClientVO> list = clientMapper.selectClient(clientQuery);
        return list;
    }
}
